package com.apes.fn.scm.retailOrder.service.orderFix;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.fn.scm.retailOrder.service.RetailOrderExtensionService;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import org.bson.Document;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.persistence.EntityManager;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author wuq
 * @Time 2022-6-17 9:36
 * @Description
 */
@Service
public class RetailSceneFlowOrderFix extends DomainService {

    @Autowired
    private EntityManager entityManager;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RetailOrderRepository orderRepository;

    private void process(SimpleRequest simpleRequest){
        entityManager.createNativeQuery(" " +
                        "SELECT ID, A.AGGREGATE_ID " +
                        "  FROM Outbox_Event_Bac_221212_wq A " +
                        " where rownum < 20 ")
                .unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .getResultStream()
                .forEach(m -> {
                    Map temp = (Map) m;
                    String id = temp.get("ID").toString();
                    String aggregate_id = temp.get("AGGREGATE_ID").toString();
                    dealData(id);
                });
    }

    private void processById(SimpleRequest request){
        dealData(request.get("id"));
    }

    private void dealData(String id){
        BasicDBObject object = new BasicDBObject();
        object.put("body", Pattern.compile("^.*"+id+".*$", Pattern.CASE_INSENSITIVE));
        FindIterable<Document> cursor = mongoTemplate.getCollection("MQueue").find(object);

        cursor.forEach((Block<? super Document>) value -> {
            JSONObject temp = JSONObject.parseObject(value.toJson());
            System.out.println(temp.getString("_id"));
            invoke("mq.message.test", MapUtil.mapper("messageId", temp.getJSONObject("_id").getString("$oid")));
        });
    }



    @Autowired
    private TransactionTemplate transactionTemplate;

    public int execute(RetailOrderExtensionService.Callback callback) {
        return transactionTemplate.execute(status -> {
            try {
                return callback.execute();
            } catch (Exception e) {
                status.isRollbackOnly();
                throw e;
            }
        });
    }

    @FunctionalInterface
    public interface Callback {
        @Nullable
        int execute();
    }


    /**
     * 修改数据
     * @param request {"page":"0", "size":"30"}
     */
    public void dealCollectData(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        int page = jsonObject.getInteger("page");
        int size = jsonObject.getInteger("size");

        Sort sort = new Sort(Sort.Direction.ASC, "create_Date");
        while (true) {
            Pageable pageable = PageRequest.of(page, size, sort);
            int execute = 0;
            try {
                execute = execute(() -> {
                    Page<Map<String, String>> maps = orderRepository.findAllForTest( pageable);
                    maps.getContent().forEach(this::dealMapData);
                    return maps.getContent().size();
                });
            } catch (Exception e) {
                //即使异常也不处理，宁愿不汇扩展表也不要影响业务
            }
            page = page + 1;
            if (execute < size) {
                break;
            }
            System.out.println("============================== page: " + page);
        }
    }

    private void dealMapData(Map map){
        String id = map.get("ID").toString();
        String aggregateId =  map.get("AGGREGATE_ID").toString();

        BasicDBObject object = new BasicDBObject();
        object.put("body", Pattern.compile("^.*"+id+".*$", Pattern.CASE_INSENSITIVE));
        FindIterable<Document> cursor = mongoTemplate.getCollection("MQueue").find(object);

        cursor.forEach((Block<? super Document>) value -> {
            JSONObject temp = JSONObject.parseObject(value.toJson());
            System.out.println("------------------------>"+ temp.getString("_id") + ", "+ aggregateId);
            invoke("mq.message.test", MapUtil.mapper("messageId", temp.getJSONObject("_id").getString("$oid")));
        });
    }
}
